package name.yzhu.wordsearch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import name.yzhu.wordsearch.WordSearch;

/**
 * the main class
 * @author yhzhu
 *
 */
public class WordSearchMain {
	public static void main(String[] args) {
		new WordSearchMain().doMain(args);
	}
	
    public void doMain( String[] args )   {
    	if (args.length == 0){
    		usage();
    		System.exit(0);
    	}
    	
    	String wordList =parseArgs(args);
    	if (wordList == null){
    		usage();
    		System.exit(0);
    	}
    	WordSearch wordSearch = new WordSearch();
    	try {
			wordSearch.open(wordList);
			runSearching(wordSearch);
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
    	finally{
    		wordSearch.close();
    	}
    	
    }

	private void runSearching(WordSearch wordSearch) throws IOException {

		BufferedReader reader = new BufferedReader(
				new InputStreamReader(System.in, "utf-8"));
		try {
			while(true){
				try{
					System.out.println("Please input the searchable word or type 'quit' to exit");
					String word = reader.readLine();
					if (word.equalsIgnoreCase("q") || word.equalsIgnoreCase("quit"))
						break;
					WordSearch.Coordinates data = wordSearch.search(word);
					if (data == null){
						System.out.println("NOT FOUND");
					}
					else {
						System.out.println(data);
					}
				}
				catch (IOException e){
					e.printStackTrace(System.err);
				}
				
			}
			System.out.println("Bye");
		} 
		finally{
			reader.close();
		}
	}

	private String parseArgs(String[] args) {
		String wordList = null;
		int nextArgsIdx = 0;
		while(nextArgsIdx < args.length){
			if (args[nextArgsIdx].equalsIgnoreCase("-file")){
				if (++nextArgsIdx < args.length)
				   wordList  = args[nextArgsIdx];
				nextArgsIdx++;
			}
			else if (args[nextArgsIdx].equalsIgnoreCase("-help")){
				break;
			}
			else {
				System.out.println("invalid option");
				break;
			}
		}
		return wordList;
	}

	private void usage() {
		System.out.println(this.getClass().getSimpleName()+" <-file wordlist> or <-help> ");
	}
    
}
